package main.java.study.串口化通信.生化仪.监听文件夹下的文件;

import lombok.extern.slf4j.Slf4j;
import study.仪器解析.串口化通信.生化仪.entity.TotalRecord;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class FolderWatcher {

//    private static final Logger log = Logger.getLogger(FolderWatcher.class.getName());

    public static void main(String[] args) throws IOException, InterruptedException {
        // 监听的文件夹路径
        Path watchDir = Paths.get("C:\\Users\\Administrator\\Desktop\\项目信息\\仪器对接\\生化仪\\文档");
        // 删除文件夹路径
        Path backupDir = Paths.get("C:\\Users\\Administrator\\Desktop\\项目信息\\仪器对接\\生化仪\\删除");

        // 开启文件夹监听
        watchDirectory(watchDir, backupDir);
    }

    // 监听文件夹变化
    public static void watchDirectory(Path watchDir, Path backupDir) throws IOException, InterruptedException {
        WatchService watchService = FileSystems.getDefault().newWatchService();

        // 注册监听器，监听创建事件
        watchDir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

        log.info("开始监听文件夹: " + watchDir.toString());

        // 无限循环监听
        while (true) {
            WatchKey key = watchService.take();
            Thread.sleep(1000);  // 延迟1秒，减少CPU占用
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();

                if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                    // 获取事件的文件名
                    Path createdPath = watchDir.resolve((Path) event.context());
                    log.info("新文件或文件夹创建: " + createdPath.toString());

                    if (Files.isDirectory(createdPath)) {
                        // 处理新创建的文件夹
                        handleNewDirectory(createdPath, backupDir, watchDir);
                    } else if (Files.isRegularFile(createdPath)) {
                        // 解析新创建的文件并删除
                        parseFileAndBackup(createdPath, backupDir, watchDir);
                    }
                }
            }
            key.reset();
        }
    }

    // 解析文件并删除
    public static void parseFileAndBackup(Path filePath, Path backupDir, Path baseDir) throws IOException {
        log.info("解析文件: " + filePath.toString());

                // 读取文件内容
        StringBuilder stringBuilder = new StringBuilder();
        String date = "";

        // 假设文件内容为文本文件，读取内容
        try (BufferedReader reader = Files.newBufferedReader(filePath)) {
            String line;
            while ((line = reader.readLine()) != null) {
                log.info("文件内容: " + line);
                stringBuilder.append(line);
            }
        }

        // 使用正则表达式来匹配 <content> 标签中的内容
        Pattern pattern = Pattern.compile("<content>(.*?)</content>");
        Matcher matcher = pattern.matcher(stringBuilder.toString());

        if (matcher.find()) {
            // 提取并打印 <content> 标签之间的内容
            date = matcher.group(1);
            System.out.println("Content: " + date);
        } else {
            System.out.println("未找到 <content> 标签");
        }

        study.仪器解析.串口化通信.生化仪.十六进制转SCALL码 hexToAsciiConverter = new study.仪器解析.串口化通信.生化仪.十六进制转SCALL码();
        String receivedData = hexToAsciiConverter.hexToAscii(date);
        System.out.println("转成SCALL码后：" + receivedData);
        study.仪器解析.串口化通信.生化仪.ASTMParser3 astmParser = new study.仪器解析.串口化通信.生化仪.ASTMParser3();
        List<TotalRecord> totalRecords = astmParser.parseASTMMessage(receivedData);

        System.out.println(totalRecords);

        // 将文件删除
        backupFile(filePath, backupDir, baseDir);
    }

    // 处理新创建的文件夹，递归处理子文件和子文件夹
    public static void handleNewDirectory(Path dirPath, Path backupDir, Path baseDir) throws IOException {
        log.info("处理新文件夹: " + dirPath.toString());

        // 遍历子文件夹和文件
        Files.walkFileTree(dirPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                // 解析并删除子文件
                parseFileAndBackup(file, backupDir, baseDir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                // 删除文件夹
                backupFile(dir, backupDir, baseDir);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    // 将文件或文件夹删除
    public static void backupFile(Path sourcePath, Path backupDir, Path baseDir) throws IOException {
        // 目标路径 = 删除目录 + 源文件相对路径
        Path relativePath = baseDir.relativize(sourcePath);
        Path targetPath = backupDir.resolve(relativePath);

        deleteFileOrDirectory(sourcePath);
    }

    // 删除文件或目录，递归删除非空目录
    public static void deleteFileOrDirectory(Path path) throws IOException {
        if (Files.isDirectory(path)) {
            // 递归删除目录中的内容
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);  // 删除文件
                    log.info("删除文件: " + file.toString());
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    Files.delete(dir);  // 删除空目录
                    log.info("删除目录: " + dir.toString());
                    return FileVisitResult.CONTINUE;
                }
            });
        } else {
            // 如果是文件，直接删除
            Files.deleteIfExists(path);
            log.info("删除文件: " + path.toString());
        }
    }
}

